package com.jh3502.vivo.function.dialog;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.jh3502.vivo.base.BaseJson;
import com.jh3502.vivo.base.BasePresenter;
import com.jh3502.vivo.base.BaseView;
import com.jh3502.vivo.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author harisucici
 * @date 2017/6/19
 */

public class PhotoChoosePresenter extends BasePresenter<PhotoChoosePresenter.PhotoChooseView> {
    PhotoChooseModel mPhotoChooseModel;

    PhotoChooseView mPhotoChooseView;


    public void setPhotoChooseView(PhotoChooseView mPhotoChooseView) {
        this.mPhotoChooseView = mPhotoChooseView;

    }


    public void toUpload(List<File> files) {
        mPhotoChooseView.showLoadingDialog();
        if (mPhotoChooseModel == null) {
            mPhotoChooseModel = new PhotoChooseModel(mPhotoChooseView.getActContext());
        }

        mPhotoChooseModel.upload(files, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mPhotoChooseView.dismissLoadingDialog();
            }

            @Override
            public void onResponse(Call call, Response response) {
                mPhotoChooseView.dismissLoadingDialog();
                Gson gson = new Gson();
                JsonReader jsonReader = new JsonReader(response.body().charStream());
                BaseJson baseJson = gson.fromJson(jsonReader, BaseJson.class);
                if (baseJson.getCode() == 0) {

                    List<String> photos = Utils.getInstance().jsa2listString(baseJson.getObj().toString());
                    mPhotoChooseView.uploadSuccess(photos.get(0));
                }
            }
        });

    }


    @Override
    public void cancelCall() {

    }

    public interface PhotoChooseView extends BaseView {
        void uploadSuccess(String s);

    }
}
